<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="新闻标题">
        <el-input
          v-model="queryParams.infoname"
          placeholder="请输入新闻标题"
          clearable
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="栏目名称">
        <el-cascader
          v-model="cat_list"
          :props="{
            value: 'categoryid',
            label: 'categoryname',
            children: 'children',
          }"
          :options="postList"
          @change="handleChangeSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <!-- <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
      </el-form-item>
    </el-form>
    <div>
      <el-button type="success" size="small" @click="add()">添加</el-button>
    </div>
    <el-table
      :data="infoList"
      stripe
      border
      style="width: 100%; margin-top: 20px; margin-bottom: 20px"
    >
      <el-table-column type="index" label="序号" width="60">
        <template slot-scope="scope">
          <span>{{
            scope.$index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="infotitle" label="新闻标题"></el-table-column>
      <el-table-column prop="author" label="作者" width="120"></el-table-column>
      <el-table-column
        prop="categoryname"
        label="所属栏目"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="addtime"
        label="发布时间"
        width="100"
      ></el-table-column>
      <el-table-column prop="checkpass" label="是否通过" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.checkpass === 1">是</span>
          <span v-if="scope.row.checkpass === 0">否</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="ordernum"
        label="排序号"
        width="70"
      ></el-table-column>
      <el-table-column label="操作" width="270">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="edit(scope.row)"
            >修改</el-button
          >
          <el-button type="danger" size="mini" @click="del(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      @size-change="handleSizeChange"
      :current-page="1"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 添加或修改新闻对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="80%"
      @closed="closeDia"
      :z-index="1001"
    >
      <el-form ref="infoRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="正文标题" prop="infotitle">
          <el-input
            v-model="form.infotitle"
            autocomplete="off"
            placeholder="默认为栏目列表及正文标题。"
          ></el-input>
        </el-form-item>
        <el-form-item label="作者/来源">
          <el-input v-model="form.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新闻图片">
          <el-upload
            accept=".jpg, .png"
            class="avatar-uploader"
            :action="uploadUrl"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            :headers="headers"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.picurl" :src="form.picurl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="摘要">
          <el-input type="textarea" v-model="form.summary"></el-input>
        </el-form-item>
        <el-form-item label="专家团队职称">
          <el-input v-model="form.jianti" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="专家团队科室">
          <el-input v-model="form.infotitle2" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新闻栏目" prop="categoryid">
          <el-cascader
            v-model="form.categoryid"
            :props="{
              value: 'categoryid',
              label: 'categoryname',
              children: 'children',
            }"
            :options="postList"
            @change="handleChangelm"
            disabled
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="form.addtime"
            type="date"
            placeholder="选择发布时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="正文">
          <VueUeditorWrap
            v-model="form.infocontent"
            :config="editorConfig"
          ></VueUeditorWrap>
          <!-- <editor v-model="form.infocontent" :min-height="192"/> -->
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number
            v-model="form.ordernum"
            placeholder="请输入排序"
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="是否发布">
          <el-radio-group v-model="form.checkpass">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否置顶">
          <el-radio-group v-model="form.shifouzhiding">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确认</el-button>
          <el-button @click="cancel">取消</el-button>
          <!-- <el-button @click="resetForm">取消</el-button> -->
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<script>
import { getToken } from "@/utils/auth";
import { listInfo, addInfo, delInfo, oneInfo, editInfo } from "@/api/yxzx/info";
import { getMenu } from "@/api/yxzx/menu";
import VueUeditorWrap from "vue-ueditor-wrap";
export default {
  components: { VueUeditorWrap },
  data() {
    return {
      loading: true,
      editorConfig: {
        serverUrl: process.env.VUE_APP_BASE_API + "/common/upload",
        UEDITOR_HOME_URL: "/UEditor/",
        zIndex: 99999,
        initialFrameHeight: 600, // 初始容器高度
        initialFrameWidth: "100%", // 初始容器宽度
      },
      queryParams: {
        catid: "",
        infoname: "",
        pageNum: 1,
        pageSize: 16,
      },
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      cat_list: [],
      postList: [],
      infoList: [],
      menu_list: [],
      total: 0,
      title: "",
      oldcat_id: "",
      open: false,
      form: {
        picurl: "",
      },
      rules: {
        infotitle: [
          { required: true, message: "请输入新闻标题", trigger: "blur" },
        ],
        categoryid: [
          { required: true, message: "请选择新闻栏目", trigger: "change" },
        ],
      },
      uploadUrl: process.env.VUE_APP_BASE_API + "/upload/UploadFujian", // 上传的图片服务器地址
      prams: {},
    };
  },
  created() {
    this.getmenuList();
  },
  methods: {
    // 表单重置
    reset() {
      this.form = {
        categoryid: "0",
        infotitle: "",
        summary: "",
        author: "",
        infocontent: "",
        picurl: "",
        jianti: "",
        infotitle2: "",
        returnurl: "",
        shifouzhiding: "",
        checkpass: "",
      };
      this.resetForm("form");
    },
    /** 查询菜单列表 */
    getmenuList() {
      this.loading = true;
      getMenu().then((response) => {
        this.loading = false;
        this.postList = this.tranListToTreeData(response.resultContent, "0");
        this.cat_list.push(this.postList[0].categoryid);
        this.queryParams.catid = this.postList[0].categoryid;
        this.getNews();
      });
    },
    // 查询新闻
    getNews() {
      this.loading = true;
      listInfo(
        this.queryParams.catid,
        this.queryParams.infoname,
        this.queryParams.pageNum,
        this.queryParams.pageSize
      ).then((response) => {
        this.infoList = response.InfoList;
        this.total = response.PageInfo.recordCount;
      });
    },
    /** 搜索选择栏目 */
    handleChangeSearch(val) {
      this.queryParams.catid = this.cat_list[this.cat_list.length - 1];
    },
    handleQuery() {
      this.getNews();
    },
    // 添加按钮
    add() {
      this.reset();
      this.open = true;
      this.form.categoryid = this.cat_list;
    },
    handleSizeChange(val) {
      this.queryParams.pageNum = val;
      this.getNews();
    },
    closeDia() {},
    handleAvatarSuccess(res, file) {
      this.form.picurl = file.response;
      // this.form.picurl = file.response.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error("上传图片格式不正确!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    /** 添加修改弹窗选择栏目 */
    handleChangelm(val) {},
    /** 改变数字 */
    handleChange(val) {
      this.form.ordernum = val;
    },
    submitForm() {
      this.$refs["infoRef"].validate((valid) => {
        if (valid) {
          if (this.form.infoid != undefined) {
            this.prams.infoid = this.form.infoid;
            this.prams.oldcategoryid = this.oldcat_id;
            this.prams.infotitle = this.form.infotitle;
            this.prams.summary = this.form.summary;
            this.prams.author = this.form.author;
            this.prams.infocontent = this.form.infocontent;
            this.prams.picurl = this.form.picurl;
            this.prams.returnurl = this.form.returnurl;
            this.prams.shifouzhiding = this.form.shifouzhiding;
            this.prams.checkpass = this.form.checkpass;
            this.prams.ordernum = this.form.ordernum;
            this.prams.jianti = this.form.jianti;
            this.prams.infotitle2 = this.form.infotitle2;
            editInfo(this.prams).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getNews();
            });
          } else {
            this.form.categoryid = this.cat_list[this.cat_list.length - 1];
            // console.log(JSON.parse(this.form))
            addInfo(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getNews();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
    },
    // 删除新闻
    del(row) {
      delInfo(row.infoid, row.categoryid).then((response) => {
        this.$modal.msgSuccess("删除成功");
        this.getNews();
      });
    },
    // 修改新闻
    edit(row) {
      oneInfo(row.infoid).then((response) => {
        this.open = true;
        this.form = response;
        this.oldcat_id = response.categoryid;
      });
    },
    tranListToTreeData(list, rootValue) {
      var arr = [];
      list.forEach((item) => {
        if (item.parentcategoryid === rootValue) {
          const children = this.tranListToTreeData(list, item.categoryid);
          if (children.length < 1) {
            item.children = undefined;
          } else {
            item.children = children;
          }
          arr.push(item);
        }
      });
      return arr;
    },
  },
};
</script>
